package cn.kgc.crowdfundingadminspringboot.controller;

import cn.kgc.crowdfundingadminspringboot.common.CrowdFundingConstant;
import cn.kgc.crowdfundingadminspringboot.common.ResultEntity;
import cn.kgc.crowdfundingadminspringboot.pojo.Admin;
import cn.kgc.crowdfundingadminspringboot.service.AdminService;
import com.github.pagehelper.PageInfo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.xml.bind.SchemaOutputResolver;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Resource
    AdminService adminService;
    @RequestMapping("/test")
    @ResponseBody
    public Admin test(Integer id){
        return adminService.selectById(id);
    }

    //处理登录
    @RequestMapping("/do/login")
    public String doLogin(String loginAcct,
                          String userPswd,
                          HttpSession session,
                          Model model){
        System.out.println("进登录方法");
        Admin admin = adminService.login(loginAcct, userPswd);
        if (admin==null){
            //登录失败
            System.out.println("登录失败");
            model.addAttribute(CrowdFundingConstant.ATTR_NAME_MESSAGE, CrowdFundingConstant.MESSAGE_LOGIN_FAILED);
            return "admin-login";
        }

        session.setAttribute(CrowdFundingConstant.ATTR_NAME_LOGIN_ADMIN,admin);
        return "redirect:/admin/to/main/page";
    }

    /**
     * 跳转后台主页面
     * @return
     */
    @RequestMapping("/to/main/page")
    public String toMain(){
        return "admin-main";
    }

    /**
     * 查询用户
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @param model
     * @return
     */
    //只能单个角色访问
    //@PreAuthorize(value="hasAnyRole('超级管理员')")
    //允许多个角色访问
    @PreAuthorize(value = "hasAnyRole('超级管理员','董事长')")
    @RequestMapping("/query/for/search")
    public String queryForSearch(
            // 如果页面上没有提供对应的请求参数，那么可以使用defaultValue指定默认值
            @RequestParam(value="pageNum", defaultValue="1",required = false) Integer pageNum,
            @RequestParam(value="pageSize", defaultValue="5",required = false) Integer pageSize,
            @RequestParam(value="keyword", defaultValue="",required = false) String keyword,
            Model model) {
        System.out.println("进查询用户的方法了");
        PageInfo<Admin> pageInfo = adminService.queryForKeywordSearch(pageNum, pageSize, keyword);
        System.out.println(pageInfo.getPageNum());
        System.out.println(pageInfo.getTotal());
        System.out.println(pageInfo.getPages());
        for (Admin admin : pageInfo.getList()){
            System.out.println(admin.getUsername());
        }
        model.addAttribute(CrowdFundingConstant.ATTR_NAME_PAGE_INFO, pageInfo);

        return "admin-page";
    }

    /**
     * 删除
     * @param adminIdList
     * @return
     */
    @ResponseBody
    @RequestMapping("/batch/remove")
    public ResultEntity<String> batchRemove(@RequestBody List<Integer> adminIdList) {
        System.out.println("进批量删除的方法了");
        try {
            adminService.batchRemove(adminIdList);
            return ResultEntity.successWithoutData();
        }catch(Exception e) {
            return ResultEntity.failed(null,e.getMessage());
        }

    }
    //跳转到新增页面
    @RequestMapping("/to/add/page.html")
    public String toAddPage(){
        return "admin-add";
    }

    /**
     * 添加用户
     * @param admin
     * @return
     */
    @RequestMapping("/save")
    public String saveAdmin(Admin admin) {

        adminService.saveAdmin(admin);

        return "redirect:/admin/query/for/search";
    }
    /**
     * 获取用户信息，跳转修改页面
     */
    @RequestMapping("/to/edit/page")
    public String toEditPage(@RequestParam("adminId") Integer adminId, Model model) {

        Admin admin = adminService.getAdminById(adminId);

        model.addAttribute(CrowdFundingConstant.ATTR_ADMIN, admin);

        return "admin-edit";
    }
    /**
     * 修改
     */
    @RequestMapping("/update")
    public String updateAdmin(Admin admin,Integer pageNum) {
        try {
            adminService.updateAdmin(admin);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/admin/query/for/search?pageNum="+pageNum;
    }

    //局部异常处理
    @ExceptionHandler(value=Exception.class)
    public String catchException(Exception exception,Model model) {
        model.addAttribute(CrowdFundingConstant.ATTR_NAME_ERROR_MESSAGE, exception.getMessage());
        return "system-error";
    }


    @RequestMapping("/admin/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index";
    }


}
